<!--
// 
// Index.vue
// rzhwweb
// 
// Created by 区区电脑 on 2024/04/08.
// 
-->
<template>
    <div :style="{height: containerHeight - 20 + 'px'}" class="Index">
        <div class="org-tree">
            <div class="head">
                <div>
                    <b-icon name="bi-diagram-3" style="margin-right: 10px" />
                    科室
                </div>
<!--                <el-checkbox v-model="hasChildren">包含子级科室</el-checkbox>-->
            </div>
            <div class="list">
                <el-tree v-if="state.orgTree" :data="state.orgTree" :default-expanded-keys="state.defaultExpandedKeys" :expand-on-click-node="false" :props="{label: 'name', children: 'children'}" highlight-current node-key="id" @node-click="onOrgSelected" />
            </div>
        </div>
<!--        <div class="user-list">-->
<!--            <div class="head">-->
<!--                <b-icon name="bi-person" style="margin-right: 10px" />-->
<!--                用户-->
<!--            </div>-->
<!--            <div class="list">-->
<!--                <div v-for="user in filterUserList" :key="user.id" :class="{active: user.id === requestBody.responsibleId}" class="user" @click="onUserSelected(user.id)">{{ user.realName }}</div>-->
<!--            </div>-->
<!--        </div>-->
        <div class="data-list">
            <table-search-bar :config="requestBodyConfig" :model="requestBody" :reset="getSearchReset" style="border-left: none;box-shadow: none;padding-left: 0" @search="searchClicked" />
            <!-- 功能按钮 -->
<!--            <div class="table-buttons">-->
<!--                <el-button v-permission="permission.add" type="primary" @click="addData">-->
<!--                    <b-icon name="bi-plus" size="20" />-->
<!--                    添加-->
<!--                </el-button>-->
<!--                &lt;!&ndash;<el-button type="warning" @click="onImportData">&ndash;&gt;-->
<!--                &lt;!&ndash;    <b-icon name="bi-cloud-upload" size="16" style="margin-right: 4px"/>&ndash;&gt;-->
<!--                &lt;!&ndash;    导入&ndash;&gt;-->
<!--                &lt;!&ndash;</el-button>&ndash;&gt;-->
<!--                <el-button type="success" @click="onExportData">-->
<!--                    <b-icon name="bi-box-arrow-right" size="13" style="margin-right: 4px" />-->
<!--                    导出-->
<!--                </el-button>-->
<!--            </div>-->
            <!--checkbox设置 :checkbox-config="{trigger: 'row', highlight: true}" -->
            <!--radio设置 :radio-config="{trigger: 'row', highlight: true}" -->
            <vxe-table ref="VXETable" :column-config="{ resizable: false}" :data="state.list" :height="containerHeight - 150" :loading="state.isLoading" :radio-config="{trigger: 'row', highlight: true}" :row-config="{isCurrent: true, isHover: true, keyField: 'id'}" :tree-config="{childrenField: 'children', reserve: true}" border round show-overflow size="small" @sort-change="onSortChange" @current-change="() => {}" @radio-change="() => {}" >
                <template #empty>
                    <el-empty :image-size="100" />
                </template>
                <!-- 通用部分 -->
                <vxe-column fixed="left" title="#" type="seq" width="50"/>
                <vxe-column align="left" field="realName" width="120" title="姓名"></vxe-column>
                <vxe-column field="count" width="100" title="登录次数"></vxe-column>
                <vxe-column field="userName" min-width="100" title="账号"></vxe-column>
            </vxe-table>
            <div class="total-row">
                登录合计：<span style="color: var(--el-color-primary)">{{totalCount}}</span> 次
            </div>
        </div>
    </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from "vue";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import * as api from "./api.js"

const props = defineProps({});
const emits = defineEmits();

// 路由
const router = useRouter();
// store
const store = useStore();

const containerHeight = computed(() => store.getters.containerHeight)
const filterUserList = computed(() => {
    if (!requestBody.orgIds) return state.userList;
    if (requestBody.orgIds.length === 0) return state.userList;
    return state.userList.filter(user => {
        return requestBody.orgIds?.findIndex(id => id === user.sysOrgId || user.orgIds.findIndex(orgId => orgId === id) > -1) > -1;
    })
})
const totalCount = ref(0)

const state = reactive({
    orgTree: [],
    userList: [],
    defaultExpandedKeys: []
})

// 当前页面功能权限
const permission = {

};


// 请求query参数
const requestParams = reactive({
    orderCol: "id",
    isDesc: true,
    pageIndex: 1,
    pageSize: 20,
});

// 请求body参数
const requestBody = reactive({

})
// 筛选区域配置
const requestBodyConfig = reactive({
    startTime: {label: "开始时间", component: "el-date-picker-datetime", format: "YYYY-MM-DD HH:mm:ss"},
    endTime: {label: "结束时间", component: "el-date-picker-datetime", format: "YYYY-MM-DD HH:mm:ss", disabledDate: (date) => new Date(date).getTime() <= new Date(requestBody.startTime).getTime()},
})
// 分页配置
const pageConfig = reactive({
    total: 0,
    sizes: [10, 20, 50, 100, 200]
})

function getSearchReset(data) {
    data.startTime = $dayjs().format("YYYY-MM-DDT00:00:00");
    data.endTime = $dayjs().format("YYYY-MM-DDTHH:mm:ss");
    return data
}

const filters = computed(() => {
    return {
        dateTime(val) {
            if (val) return $dayjs(val).format("YYYY-MM-DD HH:mm:ss")
            return ""
        }
    }
})

/**
 * 排序
 * @param column
 * @param property
 * @param order
 * @param sortBy
 * @param sortList
 * @param $event
 */
function onSortChange({column, property, order, sortBy, sortList, $event}) {
    requestParams.orderCol = property;
    requestParams.isDesc = order === "desc";
    reload(true)
}


// 点击搜索
function searchClicked() {
    console.primary("搜索条件: ", requestBody)
    reload(true);
}

// 查询列表
async function loadList() {
    const params = {
        ...requestParams
    };
    const body = {
        ...requestBody,
    };
    state.isLoading = true;
    const {success, data} = await api.GetLoginCount(body);
    state.isLoading = false;
    if (!success) return 0;
    state.list = data || [];
    let count = 0;
    state.list.map(item => {
        count += item.count;
    })
    totalCount.value = count;
}

/**
 * 分页事件
 * @param type
 */
function onPageChange({type}) {
    if (type === "current") {
        loadList();
    } else if (type === "size") {
        reload(true);
    }
}

// 刷新
function reload(resetPageIndex) {
    if (resetPageIndex) requestParams.pageIndex = 1;
    loadList()
}


const hasChildren = ref(true)

function getAllTreeId(item) {
    let ids = [item.id];
    if (item.children && item.children.length > 0) {
        for (let i = 0; i < item.children.length; i++) {
            ids = ids.concat(getAllTreeId(item.children[i]))
        }
    }
    return ids;
}

// 选中了组织
function onOrgSelected(org) {
    if (org.id === -1) {
        requestBody.orgIds = [];
    } else {
        if (hasChildren.value) {
            requestBody.orgIds = getAllTreeId(org)
        } else {
            requestBody.orgIds = [org.id];
        }
        requestBody.orgIds = requestBody.orgIds.filter(id => id);
    }

    // requestBody.responsibleId = null
    reload(true)
}

// 选中用户
function onUserSelected(id) {
    requestBody.responsibleId = id;
    reload(true)
}

function loadConfig() {
    api.GetOrgTree().then(({data = []}) => {
        state.defaultExpandedKeys = data[0] ? [data[0].id] : []
        state.orgTree = (data || []);
        state.orgTree.unshift({
            name: "全部",
            id: -1,
            children: []
        });
    })
    requestBody.endTime = $dayjs().format("YYYY-MM-DDTHH:mm:ss")
    requestBody.startTime = $dayjs().format("YYYY-MM-DDT00:00:00")
    // requestBody.startDate = $dayjs().subtract(1, 'year').format("YYYY-MM-DD")
}

onMounted(() => {
    loadConfig()
    reload(true)
})
</script>

<style lang="scss" scoped>
.Index {
    background-color: #fff;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: flex-start;
    margin: 10px;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);

    .org-tree {
        box-sizing: border-box;
        width: 260px;
        border-right: 1px solid #e0e0e0;
        height: 100%;

        .head {
            height: 40px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            box-sizing: border-box;
            padding: 0 10px;
            border-bottom: 1px solid #e0e0e0;
            color: var(--el-color-primary);
        }

        .list {
            height: calc(100% - 40px);
            overflow: auto;
        }
    }

    .user-list {
        box-sizing: border-box;
        width: 200px;
        border-right: 1px solid #e0e0e0;
        height: 100%;

        .head {
            height: 40px;
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: center;
            box-sizing: border-box;
            padding: 0 10px;
            border-bottom: 1px solid #e0e0e0;
            color: var(--el-color-primary);
        }

        .list {
            height: calc(100% - 40px);
            overflow: auto;

            .user {
                padding: 4px 10px;
                font-size: 14px;
                color: #666;
                cursor: pointer;
                user-select: none;

                &:hover {
                    background-color: var(--el-color-primary-light-9);
                }
            }

            .active {
                background-color: var(--el-color-primary-light-9);
                color: var(--el-color-primary);
            }
        }
    }

    .data-list {
        width: calc(100% - 260px);
        height: 100%;
        box-sizing: border-box;
        padding: 0 10px 10px 10px;

        .search-row {
            height: 50px;
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: center;

            .label {
                padding-right: 10px;
                font-size: 14px;
            }
        }
    }
}
</style>